package com.hns.can.master.web;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.domain.GridPage;
import com.hns.can.common.entity.BaseEntity;
import com.hns.can.common.web.BaseController;
import com.hns.can.master.component.ParseDriverInfoExcel;
import com.hns.can.master.entity.BaseDrvInfoEntity;
import com.hns.can.master.service.BaseDrvInfoService;
import com.hns.can.master.vo.DrvPostDataVo;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.mybatis.Pagination;
import com.hns.tool.export.ExportUtil;
import com.hns.tool.pub.FileUploadUtil;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.ResponseUtil;
import com.hns.tool.pub.UtilString;

/**
 * 驾驶员信息维护控制类
 * @author Lan
 *
 */
@Controller
@RequestMapping("/baseDrvInfo")
public class BaseDrvInfoController extends BaseController {
	
	/**
	 * 驾驶员信息service
	 */
	@Autowired
    private BaseDrvInfoService baseDrvInfoService;
	
	/**
	 * 导出文件表头
	 */
	private final String[] tableHeaderNames={"驾驶员姓名","所属机构","员工工号","考勤卡卡号","出生日期","性别","驾驶证类型","驾驶证号","状态"};
	/**
	 * 导出文件字段名
	 */
    private final String[] tableHeaderFields = {"drvName","organName","workEmpeEmpno","timecardCardno","birthDate","gender","driLicType","driLicNo","st"};
	
	/**
	 * 添加一个驾驶员
	 * @param entity
	 * @return
	 * @throws Exception
	 */
    @RequestMapping("/addDriverInfo")
    @ResponseBody
    public Object addDriverInfo(BaseDrvInfoEntity entity) throws Exception {
        baseDrvInfoService.addDriverInfo(entity, this.getCurrentUser().getUser());
        return this.getReturnMsg("您成功添加一个驾驶员");
    }
    
    /**
     * 得到驾驶员的page对象
     * @param dataVo
     * @return
     * @throws Exception
     */
    @RequestMapping("/searchDriverInfoPage")
    @ResponseBody
    public Object searchDriverInfoPage(DrvPostDataVo dataVo) throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        dataVo.setUserId(user.getId());
        Pagination page = baseDrvInfoService.searchDriverInfoPage(dataVo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }
    
    /**
     * 导出驾驶员信息excel
     * @param dataVo
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportDriverInfoExcel")
    @ResponseBody
    public void exportDriverInfoExcel(DrvPostDataVo dataVo, HttpServletResponse response) throws Exception {
    	dataVo.setUserId(this.getCurrentUser().getUser().getId());
    	List<BaseEntity> list = baseDrvInfoService.getDriverInfoList(dataVo);
        ExportUtil.exportFiles(Arrays.asList(tableHeaderNames), Arrays.asList(tableHeaderFields), list, response, "excel", "driverInfo", "驾驶员信息");
    }
    
    /**
     * 导出驾驶员信息pdf
     * @param dataVo
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportDriverInfoPdf")
    @ResponseBody
    public void exportDriverInfoPdf(DrvPostDataVo dataVo, HttpServletResponse response) throws Exception {
    	dataVo.setUserId(this.getCurrentUser().getUser().getId());
        List<BaseEntity> list = baseDrvInfoService.getDriverInfoList(dataVo);
        ExportUtil.exportFiles(Arrays.asList(tableHeaderNames), Arrays.asList(tableHeaderFields), list, response, "pdf", "driverInfo", "驾驶员信息");
    }
    
    /**
     * 根据驾驶员id求驾驶员信息
     * @param drvId 司机id
     * @return 驾驶员信息
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/getDriverInfoByDrvId")
    @ResponseBody
    public Object getDriverInfoByDrvId(@RequestParam(value="drvId") String drvId) throws Exception {
        BaseDrvInfoEntity entity = baseDrvInfoService.getDriverInfoByDrvId(drvId);
        return this.getReturnResult(entity);
    }
    
    /**
     * 更新驾驶员的信息
     * @param entity 司机信息
     * @return 操作返回信息
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/uptDriverInfo")
    @ResponseBody
    public Object uptDriverInfo(BaseDrvInfoEntity entity) throws Exception {
        baseDrvInfoService.uptDriverInfo(this.getCurrentUser().getUser(), entity);
        return this.getReturnMsg("保存成功");
    }
    
    /**
     * 删除一个驾驶员
     * @param drvIds 司机id
     * @return 操作返回信息
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/delDriverInfo")
    @ResponseBody
    public Object delDriverInfo(@RequestParam("drvIds") String[] drvIds) throws Exception {
        baseDrvInfoService.delDriverInfo(this.getCurrentUser().getUser(), drvIds);
        return this.getReturnMsg("驾驶员删除成功");
    }
    
    /**
     * 根据BaseDrvInfoEntity获取驾驶员列表
     * @param entity 司机信息
     * @return 驾驶员列表
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/getBaseDrvInfoList")
    @ResponseBody
    public Object getBaseDrvInfoList(BaseDrvInfoEntity entity) throws Exception {
    	List<BaseDrvInfoEntity> list = baseDrvInfoService.getBaseDrvInfoList(entity);
        return this.getReturnResult(list);
    }
    
    /**
     * 校验司机是否已和车辆绑定
     * @param drvId 司机id
     * @return 司机是否已和车辆绑定
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/validateCarDrvRel")
    @ResponseBody
    public Object validateCarDrvRel(@RequestParam("drvId") String drvId) throws Exception {
        return this.getReturnResult(baseDrvInfoService.validateCarDrvRel(drvId));
    }
    
    /**
     * @param request
     * @param response
     * @throws Exception
     * @author:Chenl
     * @email:370238764@qq.com
     * @创建日期:2015-10-19
     * @功能说明：导入文件的下载
     */
    @RequestMapping("/downloadDrvInfotemplate")
    public void downloadDrvExamImptemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = "driverInfo.xlsx";
        String targetPath = FileUploadUtil.getWebRoot(request) + "/template/" + fileName;
        File tempFile = new File(targetPath);
        if(!tempFile.exists()){
            throw new BusinessException(MsgType.WARN.getFlag(), "没有模版可以下载！");
        }
        ExportUtil.GeneratoDownFile(targetPath, fileName.substring(0,fileName.lastIndexOf('.')),".xlsx",response);
    }
    
    /**
     * 上传驾驶员信息
     * @param driverInfoFile
     * @param request
     * @return
     * @throws Exception
     * @author:Chenl
     * @email:370238764@qq.com
     */
    @RequestMapping(value = "/uploadDriverInfoFile", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadElePaperFile(
        @RequestParam MultipartFile driverInfoFile,
                HttpServletRequest request,String orgId,HttpServletResponse response) throws Exception {
    	// 将excel文件存盘
        String oldFileName = driverInfoFile.getOriginalFilename();
        String newFileName = UtilString.getUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));
        String targetPath = FileUploadUtil.getWebRoot(request) + "/template/temp/";
        FileUploadUtil.uploadFile(driverInfoFile.getInputStream(), newFileName, targetPath);
        // 解析excel文件得到list对象
        String fileName = targetPath + newFileName; // 完整路径
        File file = new File(fileName);
        SysUserEntity user = this.getCurrentUser().getUser();
        List<BaseDrvInfoEntity> list = ParseDriverInfoExcel.parseDriverInfoExcelToList(file);
        if(PubUtil.isEmpty(list)){
        	ResponseUtil.responseJSON("您导入的模版有误。", response);
        }
        //存入对应库表
        String msgs = baseDrvInfoService.saveDriverInfoToDB(list,user,orgId);
        int successCnt = baseDrvInfoService.getSuccessCount();
        // 删除临时文件
        FileUploadUtil.delFile(fileName);
        msgs = ",失败"+(list.size()-successCnt)+"条,<br/> 失败:<br/> "+msgs;
        if(successCnt == list.size()){
            msgs = "";
        }
        ResponseUtil.responseJSON(this.getReturnMsg("总共"+list.size()+"条站点数据,成功导入"+successCnt+"条"+msgs),response);
        return null;
    }

    /**
     *上传驾驶员图片
     * @param driverHead
     * @param uploadPath
     * @param drvId
     * @param request
     * @param response
     * @return
     * @throws Exception
     * @author:Chenl
     * @email:370238764@qq.com
     * @创建日期:2017-03-31
     */
    @RequestMapping(value = "/uploadDriverHead", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadDriverHead(@RequestParam MultipartFile[] driverHead,String uploadPath, String drvId,HttpServletRequest request,HttpServletResponse response) throws Exception{
        baseDrvInfoService.returnDrvHeadPath(driverHead,uploadPath,drvId,request,response);
        return null;
    }

}
